﻿using System.Collections.Generic;
using System.Diagnostics;
using System.Collections.Concurrent;

namespace TfsGiggle.Core
{
    /// <summary>
    /// Holds most n recent items
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class RecentList<T> : ConcurrentStack<T>
    {
        int _size = -1;

        private RecentList() { }

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="size"></param>
        public RecentList(int size)
        {
            Debug.Assert(size > 0);
            _size = size;
        }

        /// <summary>
        /// Add item, remove items that exceed _size
        /// </summary>
        /// <param name="item"></param>
        public void Add(T item)
        {
            Push(item);
            Trim();
        }

        private void Trim()
        {
            T item;
            while (Count > _size)
            {
                this.TryPop(out item);
            }
        }
    }
}
